//
//  JrdCourseListViewController.m
//  v2ex-iOS
//
//  Created by longcheng on 16/5/20.
//  Copyright © 2016年 Singro. All rights reserved.
//

#import "JrdCourseListViewController.h"
#import "JrdCommon.h"
#import "JRDCourseCell.h"
#import "JrdCourseDetailViewController.h"
#import "MJRefresh.h"
#import "CKHttpCommunicate.h"
#import "JZCateModel.h"
#import "LiuXSegmentView.h"
#import "LCCSqliteManager.h"
#import "JrdDatamanager.h"
#import "JrdSelCourseModel.h"
@interface JrdCourseListViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray *courseLastest;
    NSMutableArray *courseMostPopular;
    NSMutableArray *courseReconmmend;
    NSMutableArray *courseSel;
    NSMutableArray *openedinSectionArr;
    //NSMutableArray *courseSelect;
    NSMutableArray *courseAva;
    NSInteger segSelectType;
    NSInteger _page;/**< 页数 */
    NSInteger _limit;/**< 每页的个数 */
    NSInteger _charge;/**< 1：免费；2：收费 */
    NSInteger sql_count;
    NSArray* cache_data_array;
    NSArray* cache_data_array_ava;
    UIButton* _button;
    NSString* startDate;
    NSString* endDate;
    NSMutableArray* sectionArray;
    NSMutableArray* rowArray;
    NSArray* course_;
    //NSMutableArray* selectCourseCategotyId;
    LCCSqliteManager* manager;
    int send_tag;
}
@property (nonatomic, strong) SCBarButtonItem *leftBarItem;
@property (nonatomic, strong) SCBarButtonItem *rightBarItemExpend;
@property (nonatomic, strong) UITableView* tableView;
@property (assign, nonatomic) NSIndexPath *selIndex;//单选，当前选中的行did
@end

@implementation JrdCourseListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.sc_navigationItem.leftBarButtonItem = self.leftBarItem;
    self.sc_navigationItem.rightBarButtonItem = self.rightBarItemExpend;
    segSelectType = JRD_COURSE_LASTEST;
    courseSel = [[NSMutableArray alloc] init];
    courseAva = [[NSMutableArray alloc] init];
    openedinSectionArr = [[NSMutableArray alloc] init];
    _courseSelect = [[NSMutableArray alloc] init];
    sectionArray = [[NSMutableArray alloc] init];
    rowArray = [[NSMutableArray alloc] init];
    manager = [LCCSqliteManager shareInstance];
    //[manager openSqliteFile:@"database"];
    NSString* where_select = [NSString stringWithFormat:@"course_category=%@ and user_id=%@",@"'selectd'", [JrdDatamanager manager].user.userId];
    cache_data_array = [manager searchDataFromSheet:@"courselist" where:where_select];
    
    NSString* where_not_select = [NSString stringWithFormat:@"course_category!=%@",@"'selectd'"];
    cache_data_array_ava = [manager searchDataFromSheet:@"courselist" where:where_not_select];
}

- (void)initData{
    segSelectType = JRD_COURSE_LASTEST;
    _page = 1;
    _limit = 20;
    _charge = 1;
}

- (void)viewDidAppear:(BOOL)animated{
    self.sc_navigationItem.title = NSLocalizedString(@"v2_select_center",nil);//@"我们学习";
}

- (void)loadView{
    [super loadView];
    [self configureNavibarItems];
    [self configureSegTable];
    [self configureTable];
}

#pragma mark - Navigation
- (void)configureNavibarItems {
    self.leftBarItem = [[SCBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico-menu"] highlight:[UIImage imageNamed:@"ico-menu"] style:SCBarButtonItemStylePlain handler:^(id sender) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowMenuNotification object:nil];
    }];
    /*self.rightBarItemExpend = [[SCBarButtonItem alloc] initWithTitle:@"Done" style:SCBarButtonItemStylePlain handler:^(id sender){
        [self dismissViewControllerAnimated:YES completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:kGotoMyLearnNotification object:nil];
    }];*/
}

#pragma mark - segmentcontroller
- (void)configureSegTable{
    
    UIView* segView = [[UIView alloc] initWithFrame:CGRectMake(0, STATUS_BAR_HEIGHT+NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, STUDY_VIEW_SECTION_H)];
    [segView setBackgroundColor:JrdNavigationBarColor];//JRD_RGB(67, 199, 176)];
    [self.view addSubview:segView];
    
    LiuXSegmentView *view=[[LiuXSegmentView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)        titles:@[NSLocalizedString(@"v2_latest_publish",nil)/*,NSLocalizedString(@"v2_most_popular", nil)*/,NSLocalizedString(@"v2_recommend", nil)]
                                                          offset: 20
                                                      clickBlick:^void(NSInteger index) {
                                                          [self tagClick:index];
                                                      }];
    [segView addSubview:view];

}

- (void)tagClick: (NSInteger)index{
    segSelectType =index;
    if((JRD_COURSE_LASTEST == segSelectType && nil == courseLastest)){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }
    
    if(JRD_COURSE_MOST_POPULAR == segSelectType && nil == courseMostPopular){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }
    
    if(JRD_COURST_RECOMMEND == segSelectType && nil == courseReconmmend){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }
    
}


- (void)segmentedControlChangedValue: (UISegmentedControl*)sendrer{
    segSelectType =sendrer.selectedSegmentIndex;
    if((JRD_COURSE_LASTEST == segSelectType && nil == courseLastest)){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }
    
    if(JRD_COURSE_MOST_POPULAR == segSelectType && nil == courseMostPopular){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }

    if(JRD_COURST_RECOMMEND == segSelectType && nil == courseReconmmend){
        [self.tableView.mj_header beginRefreshing];
        [self loadNewData];
    }else{
        [self.tableView reloadData];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - set table

-(void)configureTable{
    int table_y = STATUS_BAR_HEIGHT+NAVIGATION_BAR_HEIGHT+STUDY_VIEW_SECTION_H;//_section_view.frame.origin.y + _section_view.frame.size.height;
    self.tableView                 = [[UITableView alloc] initWithFrame:CGRectMake(0, table_y, SCREEN_WIDTH, SCREEN_HEIGHT - table_y) style:UITableViewStylePlain];
    //self.tableView.style = UITableViewStylePlain;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setupTableview];
}

- (void)loadNewData{
    _page = 1;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getCourseData];
    });
}

- (void)loadMoreData{
    _page++;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getCourseData];
    });
    
}

-(void)setupTableview{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //设置普通状态的动画图片
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=60; ++i) {
        //        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_anim__000%zd",i]];
        //        [idleImages addObject:image];
        UIImage *image = [UIImage imageNamed:@"icon_listheader_animation_1"];
        [idleImages addObject:image];
    }
    [header setImages:idleImages forState:MJRefreshStateIdle];
    
    //设置即将刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    UIImage *image1 = [UIImage imageNamed:@"icon_listheader_animation_1"];
    [refreshingImages addObject:image1];
    UIImage *image2 = [UIImage imageNamed:@"icon_listheader_animation_2"];
    [refreshingImages addObject:image2];
    [header setImages:refreshingImages forState:MJRefreshStatePulling];
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
    self.tableView.mj_header = header;
    //马上进入刷新状态
    //[self.tableView.mj_header beginRefreshing];
    //数据库没有数据的时候，从网络获取
    [self loadNewData];
}

#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([[openedinSectionArr objectAtIndex:section] intValue] == 1) {
        return 0;
    }else{
        NSMutableArray*array =  courseAva[section];
        return array.count;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    int cSel = 0;
    return courseAva.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return JRD_COURSE_TABLE_H;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIndentifier = @"courseCell2";
    JRDCourseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[JRDCourseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        //下划线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 71.5, SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = JRD_RGB(200, 199, 204);
        [cell addSubview:lineView];
    }
    JrdCourseModel *jrdCourseM = [[JrdCourseModel alloc] init];
        //has no coursesel
        NSMutableArray* array = courseAva[indexPath.section];
        jrdCourseM.courseName = [array[indexPath.row] valueForKey:@"course"];
        jrdCourseM.courseDes = [array[indexPath.row] valueForKey:@"description"];
        NSString* url_icon = [array[indexPath.row] valueForKey:@"icon_url"];
    
        NSString* courseId= [array[indexPath.row]valueForKey:@"course_id"];
        NSString * searchCondition = [NSString stringWithFormat:@"course_id=%@ and user_id=%@",
                                  courseId,[JrdDatamanager manager].user.userId];
        course_= [manager searchDataFromSheet:@"courselist" where:searchCondition];

        jrdCourseM.coursePhoto = [NSString stringWithFormat:@"http://120.55.86.220/%@",url_icon];
        
        UIButton *button= [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 50, (JRD_COURSE_TABLE_H - 30)/2, 45, 30)];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 3;
        [button.layer setBorderWidth:1.0f];
        NSNumber* section = [NSNumber numberWithLong:indexPath.section];
        NSNumber* row = [NSNumber numberWithLong:indexPath.row];
        if(([sectionArray containsObject:section]&& [rowArray containsObject:row]) ||[course_[0][COURSE_IS_SELECT] compare:@"1"] == NSOrderedSame ){
            //button.enabled= false;
            [button setTitle:NSLocalizedString(@"jrd_cancel",nil) forState:UIControlStateNormal];
                
            [button setBackgroundColor:[UIColor whiteColor]];
            button.layer.borderColor =[[UIColor redColor] CGColor];
        }else{
            [button setTitle:NSLocalizedString(@"jrd_learn",nil) forState:UIControlStateNormal];
            [button setBackgroundColor:[UIColor whiteColor]];
            [button.layer setBorderColor:[[UIColor redColor] CGColor]];
        }
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont systemFontOfSize:14.f]];
        button.tag = indexPath.section*10 + indexPath.row+10;
        [button addTarget:self action:@selector(learnClick:) forControlEvents:UIControlEventTouchUpInside];

        for(int i = 0; i < courseSel.count;i++)
        {

            NSString* course_name = [array[indexPath.row] valueForKey:@"course"];
            NSString* category = [array[indexPath.row] valueForKey:@"category_id"];

            JrdSelCourseModel* model = courseSel[i];//[[JrdSelCourseModel alloc] init];
            
            if([model.course_name isEqualToString:course_name] && [model.category_id isEqualToString:category]){
                NSLog(@"zlwu %ld, %ld", (long)indexPath.section, (long)indexPath.row);
                cell.accessoryView = button;
                break;
            }else{
                if(JRD_CHECK_VALUE == [[JrdDatamanager manager] getCheckValue]){
                    cell.accessoryView = button;
                }else{
                    cell.accessoryView = nil;
                }
            }
        }
    [cell setJzCourseM:jrdCourseM];
    return cell;
}

- (void)learnClick:(UIButton*)sender{
    NSNumber* section = [NSNumber numberWithLong:((sender.tag - 10)/10)];
    NSNumber* row = [NSNumber numberWithLong:((sender.tag - 10)%10)];
    UIButton *button = (UIButton*)[self.view viewWithTag:sender.tag];
    NSMutableArray*array =  courseAva[[section intValue]];
    [sectionArray addObject:section];
    [rowArray addObject:row];
    
    send_tag = sender.tag;
    //update db
    NSString* course_id = [array[[row intValue]] valueForKey:@"course_id"];
    //update by course id
    NSString * searchConditionExt = [NSString stringWithFormat:@"course_id=%@ and user_id=%@",
                                     course_id,[JrdDatamanager manager].user.userId];

    
    int index = [row intValue];
    NSString* courseId= [array[index]valueForKey:@"course_id"];
    NSString * searchCondition = [NSString stringWithFormat:@"course_id=%@ and user_id=%@",
                                  courseId,[JrdDatamanager manager].user.userId];
    course_= [manager searchDataFromSheet:@"courselist" where:searchCondition];

    if([course_[0][COURSE_IS_SELECT] compare:@"1"] == NSOrderedSame){
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"jrd_couse_cancel_selected", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_cancel", nil) otherButtonTitles:NSLocalizedString(@"jrd_done", nil)   , nil];
        [alert show];

    }else{
        [button setBackgroundColor:[UIColor whiteColor]];
        button.layer.borderColor =[[UIColor redColor] CGColor];
        [button setTitle:NSLocalizedString(@"jrd_cancel", nil) forState:UIControlStateNormal];
        Boolean retExt = [manager updateDataToSheet_couse_select:@"courselist" withData:@[@(1)] where:searchConditionExt];
        NSLog(@"%hhu", retExt);
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"jrd_couse_selected", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_done", nil) otherButtonTitles:nil, nil];
        [alert show];
        [[NSNotificationCenter defaultCenter] postNotificationName:kSelectCourseNotification object:self];

    }
    
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if(1 == buttonIndex){
        NSNumber* section = [NSNumber numberWithLong:((send_tag - 10)/10)];
        NSNumber* row = [NSNumber numberWithLong:((send_tag - 10)%10)];
        NSMutableArray*array =  courseAva[[section intValue]];
        NSString* course_id = [array[[row intValue]] valueForKey:@"course_id"];
        //update by course id
        NSString * searchConditionExt = [NSString stringWithFormat:@"course_id=%@ and user_id=%@",
                                         course_id,[JrdDatamanager manager].user.userId];
        Boolean retExt = [manager updateDataToSheet_couse_select:@"courselist" withData:@[@(0)] where:searchConditionExt];
        if(YES == retExt){
            UIButton *button = (UIButton*)[self.view viewWithTag:send_tag];
            [button setBackgroundColor:[UIColor whiteColor]];
            button.layer.borderColor =[[UIColor redColor] CGColor];
            [button setTitle:NSLocalizedString(@"jrd_learn", nil) forState:UIControlStateNormal];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kSelectCourseNotification object:self];

    }
}
#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //NSMutableArray* value = nil;
    /*if(0 != indexPath.section){
        return;
    }*/
    //if(0 != courseSel.count){
        //go to chapter detail screen
        NSLog(@"didselect row ");
        //记录当前选中的位置索引
        _selIndex = indexPath;
        //当前选择的打勾
        JrdCourseModel* jrdCoursmodel = [[JrdCourseModel alloc] init];
        jrdCoursmodel.courseName = [courseAva[indexPath.section][indexPath.row] valueForKey:@"course"];
        jrdCoursmodel.courseDes =[courseAva[indexPath.section][indexPath.row] valueForKey:@"description"];
        NSString* url_icon = [courseAva[indexPath.section][indexPath.row] valueForKey:@"icon_url"];
        jrdCoursmodel.coursePhoto = [NSString stringWithFormat:@"http://120.55.86.220/%@",url_icon];
        jrdCoursmodel.courseId = [courseAva[indexPath.section][indexPath.row]  valueForKey:@"course_id"];
        jrdCoursmodel.courseStartTime =[courseAva[indexPath.section][indexPath.row]  valueForKey:@"startDate"];
        jrdCoursmodel.courseEndTime =[courseAva[indexPath.section][indexPath.row]  valueForKey:@"endDate"];

        JrdCourseDetailViewController* vc = [[JrdCourseDetailViewController alloc] init];
        vc.coursemodel = jrdCoursmodel;
        vc.enter_type = ENTER_FROM_VIEWONLY;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    //}
    
    /*UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"jrd_no_permission", nil) message:NSLocalizedString(@"jrd_no_permission_des", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];
    alertView.frame  = CGRectMake((SCREEN_WIDTH - 200)/2, (SCREEN_HEIGHT - 150)/2, 200, 100);
    alertView.tag = 0;
    [alertView show];*/
}

#pragma mark - setFakeData
- (void)setFakeData{
    courseLastest = [[NSMutableArray alloc] init];
    courseMostPopular = [[NSMutableArray alloc] init];
    courseReconmmend = [[NSMutableArray alloc] init];
    
    //读取plist文件获取假数据
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"classCategory" ofType:@"plist"];
    courseLastest = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    
    //课程类型
    NSString *iCategoryListPath = [[NSBundle mainBundle] pathForResource:@"courseSel" ofType:@"plist"];
    courseMostPopular = [[NSMutableArray alloc] initWithContentsOfFile:iCategoryListPath];
    
    NSString *recommendPath = [[NSBundle mainBundle] pathForResource:@"classCategory" ofType:@"plist"];
    courseReconmmend = [[NSMutableArray alloc] initWithContentsOfFile:recommendPath];
}

#pragma mark - fake data
- (void)getCourseData{
    NSDictionary *parameter;
    parameter =@{
                 @"userid":[JrdDatamanager manager].user.userId
                 };
    __weak typeof(self) weakself = self;
    [CKHttpCommunicate createRequest:HTTP_COURSE_DATA WithParam:parameter withMethod:GET success:^(id result) {
        if (result) {
            [courseSel removeAllObjects];
            [courseAva removeAllObjects];
            NSMutableArray *CourseSelListArray = [result objectForKey:@"SelectedCourses:"];
            for(int i = 0; i < CourseSelListArray.count; i++){
                JrdSelCourseModel* model = [[JrdSelCourseModel alloc] init];
                model.course_name = [[CourseSelListArray objectAtIndex:i] valueForKey:@"course"];//category_id
                model.category_id = [[CourseSelListArray objectAtIndex:i] valueForKey:@"category_id"];//category_id
                model.startDate =[[CourseSelListArray objectAtIndex:i] valueForKey:@"startDate"];
                model.endDate = [[CourseSelListArray objectAtIndex:i] valueForKey:@"endDate"];
                [courseSel addObject:model];
            }
            
            NSMutableArray *CourseAvaListArray = [result objectForKey:@"AvailableCourses:"];
            NSMutableArray* avaArray = [[NSMutableArray alloc] init];
            NSString* preModelCategory;
            for(int i = 0; i < CourseAvaListArray.count; i++){
                NSDictionary* array_get=[CourseAvaListArray objectAtIndex:i];
                NSMutableDictionary* array = [NSMutableDictionary dictionaryWithDictionary:array_get];
                NSString* currentCategory = [array valueForKey:@"category"];
                
                NSDictionary* startDic = [NSDictionary dictionaryWithObject:@"" forKey:@"startDate"];
                NSDictionary* endDic = [NSDictionary dictionaryWithObject:@"" forKey:@"endDate"];
                [array addEntriesFromDictionary:startDic];
                [array addEntriesFromDictionary:endDic];
                
                for(int i = 0; i < courseSel.count; i++){
                    JrdSelCourseModel* model = courseSel[i];//[[JrdSelCourseModel alloc] init];
                    if([model.course_name isEqualToString:[array valueForKey:@"course"]] && [model.category_id isEqualToString:[array valueForKey:@"category_id"]]){
                        //NSDictionary* startDic = [NSDictionary dictionaryWithObject:model.startDate forKey:@"startDate"];
                        //NSDictionary* endDic = [NSDictionary dictionaryWithObject:model.endDate forKey:@"endDate"];
                        [array setValue:model.startDate forKey:@"startDate"];
                        [array setValue:model.endDate forKey:@"endDate"];
                        break;
                    }
                }

                if(nil == preModelCategory || ![preModelCategory isEqualToString:currentCategory]){
                    preModelCategory = currentCategory;//model.courseCategory;
                    avaArray = [[NSMutableArray alloc] init];
  
                    [avaArray addObject:array];
                    [courseAva addObject:avaArray];
                }else{
                    [avaArray addObject:array];
                }
                
                
                NSString* startDate_v  = @"";
                NSString* endDate_v = @"";
                NSString * searchCondition = [NSString stringWithFormat:@"course_id=%@ and user_id=%@",[CourseAvaListArray[i] valueForKey:@"course_id"],[JrdDatamanager manager].user.userId];
                NSArray* arraySearch = [manager searchDataFromSheet:@"courselist" where:searchCondition];
                NSString* course_name =[array valueForKey:@"course"];
                NSString* category = [array valueForKey:@"category_id"];
                for(int i = 0; i < courseSel.count; i++){
                    JrdSelCourseModel* model = courseSel[i];//[[JrdSelCourseModel alloc] init];
                    if([model.course_name isEqualToString:course_name] && [model.category_id isEqualToString:category]){
                        startDate_v = model.startDate;
                        endDate_v = model.endDate;
                        break;
                    }
                }
                
                if(nil == arraySearch|| 0 == arraySearch.count){
                    Boolean ret = [manager insertDataToSheet:@"courselist" withData:@[
                                  [JrdDatamanager manager].user.userId,
                                  [CourseAvaListArray[i]  valueForKey:@"course_id"],
                                  [CourseAvaListArray[i]  valueForKey:@"course"],
                                  [CourseAvaListArray[i]  valueForKey:@"description"],
                                   @"selectd",
                                  startDate_v,
                                  endDate_v,
                                  [CourseAvaListArray[i]  valueForKey:@"icon_url"],
                                  @(0), //0 not, 1 selected, 2 download
                                  @(0),
                                  @""
                              ]];
                    NSLog(@"ret = %d", ret);
                }else{
                    //update database
                    NSString * searchCondition1 = [NSString stringWithFormat:@"course_id=%@ and user_id=%@",arraySearch[0][COURSE_ID],[JrdDatamanager manager].user.userId];

                    Boolean ret = [manager updateDataToSheet_CourseList:@"courselist" withData:@[
                                    [CourseAvaListArray[i]  valueForKey:@"course"],
                                    [CourseAvaListArray[i]  valueForKey:@"description"],
                                    @"selectd",
                                    startDate_v,
                                    endDate_v,
                                    [CourseAvaListArray[i]  valueForKey:@"icon_url"],
                                    ] where:searchCondition1];
                    NSLog(@"ret = %d", ret);

                }
                
                NSArray* array1 = [manager getSheetDataWithSheet:@"courselist"];
                NSLog(@"test");
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:kSelectCourseNotification object:self];
            NSLog(@"result:%@",result);
            for(int i = 0 ; i < courseAva.count;i++){
                [openedinSectionArr addObject:@(0)];
            }
        }
        [weakself.tableView reloadData];
        [weakself.tableView.mj_header endRefreshing];
        [weakself.tableView.mj_footer endRefreshing];
    } failure:^(NSError *erro) {
        
    } showHUD:nil];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return JRD_COURSE_SECTION_H;
}

- (void)tapHeader:(UIButton*)sender{
    NSLog(@"zlwu add for tap Header");
    if ([[openedinSectionArr objectAtIndex:sender.tag - 100] intValue] == 0) {
        [openedinSectionArr replaceObjectAtIndex:sender.tag - 100 withObject:@"1"];
        //NSLog(@"%d打开",sender.tag);
    }
    else
    {
        [openedinSectionArr replaceObjectAtIndex:sender.tag - 100 withObject:@"0"];
        //NSLog(@"%d关闭",sender.tag);
    }
    
    [self.tableView reloadData];
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * mySectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, JRD_COURSE_SECTION_H)];
    mySectionView.backgroundColor = JrdTableHeadColor;//[UIColor orangeColor];
    UIButton * myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //myButton.imageView.image = [UIImage imageNamed:@"淡蓝头.png"];
    myButton.frame = CGRectMake(0, 0, SCREEN_WIDTH, JRD_COURSE_SECTION_H);
    myButton.tag = 100 + section;
    [myButton addTarget:self action:@selector(tapHeader:) forControlEvents:UIControlEventTouchUpInside];
    [mySectionView addSubview:myButton];
    
    UILabel * myLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, (SCREEN_WIDTH - 20), JRD_COURSE_SECTION_H)];
    myLabel.backgroundColor = [UIColor clearColor];
    NSString* label_text;
    /*if(0 != courseSel.count) // has select
    {
        if(0 == section){
            label_text =  NSLocalizedString(@"jrd_selected_course", nil);//@"selected course";
        }else{
            NSMutableArray* array = courseAva[section - 1];
            NSString* categoty = [array[0] objectForKey:@"category"];
            label_text = categoty;
        }
    }else{*/
        //no select
        NSMutableArray* array = courseAva[section];
        NSString* categoty = [array[0] objectForKey:@"category"];
        label_text = categoty;
        
    //}
    myLabel.text  = label_text;

    [myButton addSubview:myLabel];
    
    return mySectionView;
}


- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section   // fixed font style. use custom view (UILabel) if you want something different
{
    if(0 != courseSel.count) // has select
    {
        if(0 == section){
            return NSLocalizedString(@"jrd_selected_course", nil);//@"selected course";
        }else{
            NSMutableArray* array = courseAva[section - 1];
            NSString* categoty = [array[0] objectForKey:@"category"];
            return categoty;
        }
    }else{
        //no select
        NSMutableArray* array = courseAva[section];
        NSString* categoty = [array[0] objectForKey:@"category"];
        return categoty;

    }
}
@end

